#!/usr/bin/env python3
"""
数据验证脚本 - 检查Shopify同步数据是否存在于数据库中
"""

import os
import sys
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import asyncio
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


async def check_shopify_data():
    """检查数据库中的Shopify同步数据"""
    try:
        # 导入必要的模块
        from database.connection import get_session
        from database.models import Product, Order, ShopifySyncLog
        from sqlmodel import select
        
        logger.info("开始检查数据库中的Shopify同步数据...")
        
        # 使用异步会话
        async for session in get_session():
            try:
                # 检查带Shopify ID的商品
                stmt = select(Product).where(Product.shopify_product_id.isnot(None))
                result = await session.execute(stmt)
                shopify_products = result.scalars().all()
                
                logger.info(f"数据库中发现 {len(shopify_products)} 个来自Shopify的商品")
                for i, product in enumerate(shopify_products[:5]):
                    logger.info(f"  商品 {i+1}: {product.name} (Shopify ID: {product.shopify_product_id})")
                
                # 检查带Shopify ID的订单
                stmt = select(Order).where(Order.shopify_order_id.isnot(None))
                result = await session.execute(stmt)
                shopify_orders = result.scalars().all()
                
                logger.info(f"数据库中发现 {len(shopify_orders)} 个来自Shopify的订单")
                for i, order in enumerate(shopify_orders[:5]):
                    logger.info(f"  订单 {i+1}: {order.order_number} (Shopify ID: {order.shopify_order_id})")
                
                # 检查同步日志
                stmt = select(ShopifySyncLog).order_by(ShopifySyncLog.created_at.desc()).limit(10)
                result = await session.execute(stmt)
                sync_logs = result.scalars().all()
                
                logger.info(f"数据库中发现 {len(sync_logs)} 条同步日志记录")
                for i, log in enumerate(sync_logs[:5]):
                    logger.info(f"  日志 {i+1}: {log.shopify_resource_type} {log.shopify_operation} {log.sync_status}")
                
                # 总结
                if len(shopify_products) > 0 or len(shopify_orders) > 0:
                    logger.info("✅ 成功! Shopify数据已成功同步到后端数据库")
                    logger.info("您现在可以在后台管理页面查看这些数据了")
                else:
                    logger.warning("⚠️ 警告: 数据库中未发现来自Shopify的商品或订单")
                    logger.info("可能的原因:")
                    logger.info("1. Shopify API配置不完整，正在使用模拟数据")
                    logger.info("2. Shopify店铺中没有商品或订单数据")
                    logger.info("3. 同步过程中出现了错误")
                    logger.info("请检查同步日志获取更多信息")
                
            except Exception as e:
                logger.error(f"查询数据库时出错: {e}")
    
    except Exception as e:
        logger.error(f"执行数据检查时出错: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    asyncio.run(check_shopify_data())
    logger.info("数据验证完成")